import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import * as requestIp from 'request-ip';

@Catch()
export class AllExceptionFilter implements ExceptionFilter {
    private readonly logger = new Logger();

    constructor(private readonly HttpAdapter: HttpAdapterHost) {}

    catch(exception: unknown, host: ArgumentsHost) {
        const { httpAdapter } = this.HttpAdapter;
        const ctx = host.switchToHttp();
        const request = ctx.getRequest<Record<string, any>>();
        const response = ctx.getResponse<Record<string, any>>();
        const httpStatus = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
        const clientIp = requestIp.getClientIp(request as requestIp.Request);

        const responseBody = {
            headers: request.headers as Record<string, string>,
            query: request.query as Record<string, string>,
            body: request.body as Record<string, any>,
            params: request.params as Record<string, string>,
            timestamp: new Date().toISOString(),
            ip: (clientIp as string) || 'unknown',
            exceptioin: exception instanceof Error ? exception.name : 'UnknownError',
            error: exception instanceof Error ? exception.message : 'Internal Server Error',
        };

        this.logger.error('[dandan]', responseBody);
        httpAdapter.reply(response, responseBody, httpStatus);
    }
}
